package cn.ekuma.android.driver;

import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.util.Log;

import com.openbravo.pos.printer.TicketPrinterException;
import com.openbravo.pos.printer.escpos.PrinterWritter;

public class PrinterWritterUsb extends PrinterWritter /* implements SerialPortEventListener */ {
    
	private static int TIMEOUT = 0;
	
    UsbDevice device;
    UsbManager mUsbManager;
    UsbDeviceConnection mConnection;
    UsbEndpoint ep;
    
    /** Creates a new instance of PrinterWritterComm */
    public PrinterWritterUsb(UsbManager mUsbManager,UsbDevice device) throws TicketPrinterException {
    	this.device=device;
    	this.mUsbManager=mUsbManager;
    }

	protected void internalWrite(byte[] data) {
		
		if (mConnection == null) {
			if (device.getInterfaceCount() != 1) {
				// Log.e(TAG, "could not find interface");

			}
			UsbInterface intf = device.getInterface(0);

			// device should have one endpoint
			if (intf.getEndpointCount() != 1) {
				// Log.e(TAG, "could not find endpoint");

			}
			// endpoint should be of type interrupt
			ep = intf.getEndpoint(1);

			// if (ep.getType() != UsbConstants.USB_ENDPOINT_XFER_INT) {
			// Log.e(TAG, "endpoint is not interrupt type");
			// memo.append("endpoint is not interrupt type");
			// return;
			// }

			if (device != null) {
				UsbDeviceConnection connection = mUsbManager.openDevice(device);
				if (connection != null && connection.claimInterface(intf, true)) {
					// Log.d(TAG, "open SUCCESS");
					mConnection = connection;
					int count = mConnection.bulkTransfer(ep, data, data.length,
							TIMEOUT);
				} else {
					// Log.d(TAG, "open FAIL");
					mConnection = null;
				}
			}
		}else{
			int count = mConnection.bulkTransfer(ep, data, data.length,TIMEOUT);
		}
		
    }
    
    protected void internalFlush() {
       
    }
    
    protected void internalClose() {
        
    }
}